﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using Tesla.Math;

namespace Tesla.Graphics {
    /// <summary>
    /// Opaque bucket comparer that will sort renderables based on their material. If those
    /// are equal, or the comparison isn't applicable, then they are sorted front-to-back.
    /// </summary>
    public sealed class OpaqueRenderBucketComparer : IRenderBucketComparer {
        private IRenderer _renderer;

        /// <summary>
        /// Creates a new OpaqueRenderBucketComparerer.
        /// </summary>
        /// <param name="renderer">Renderer to use</param>
        public OpaqueRenderBucketComparer(IRenderer renderer) {
            _renderer = renderer;
        }

        /// <summary>
        /// Compares two renderable's by their material or if that is equal,
        /// then which is closer to the camera. If
        /// x is less than y, -1 is returned. If x is greater than y, 1 
        /// is returned. If they're equal then 0 is returned.
        /// </summary>
        /// <param name="x">First renderable</param>
        /// <param name="y">Second renderable</param>
        /// <returns>Comparision result</returns>
        public int Compare(IRenderable x, IRenderable y) {
            //Compare materials, if applicable.
            if(x != null && y != null) {
                int result = x.Material.CompareTo(y.Material);
                if(result != 0) {
                    return result;
                }
            }

            //Otherwise if not, or materials are equal, do front-back ordering
            float dist1 = DistanceToCamera(x);
            float dist2 = DistanceToCamera(y);

            if(dist1 < dist2) {
                return -1;
            } else if(dist1 > dist2) {
                return 1;
            } else {
                return 0;
            }
        }

        //Distance method that modulates the distance from the world pos
        //to the cam's pos by the cam's current view angle to prefer objects
        //closer to the center of view. (inspired from jMonkey)
        private float DistanceToCamera(IRenderable s) {
            if(s == null) {
                return float.NegativeInfinity;
            }

            ICamera cam = _renderer.CurrentCamera;
            Vector3 camPos = cam.Position;
            Vector3 camDir = cam.Direction;

            Vector3 worldPos = s.WorldTransform.Translation;
            Vector3 distVector;
            float retVal;
            float temp;

            Vector3.Subtract(ref worldPos, ref camPos, out distVector);
            Vector3.Dot(ref distVector, ref camDir, out retVal);
            Vector3.Dot(ref camDir, ref camDir, out temp);

            retVal = System.Math.Abs(retVal / temp);
            Vector3.Multiply(ref camDir, retVal, out distVector);

            return distVector.Length();
        }
    }
}
